//
//  MessageViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/10/10.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "MessageViewController.h"
#import "MessageTableViewCell.h"
#import "WeChatLoginViewController.h"
@interface MessageViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)NSMutableArray * cellArr;
@property (nonatomic, assign)int currentPage;
@property (nonatomic, strong)NSString * urlStr;
@property (nonatomic, strong)NSString * deleteMsgID;//删除信息id
@property (nonatomic, assign)int deleteRow;//删除行
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * tokenString;
- (void)ifLogin;
@end

@implementation MessageViewController(networking)
- (void)getMessageData{
    NSDictionary * dic = @{
                           @"phone":self.phoneString,
                           @"token":self.tokenString,
                           @"page":@(self.currentPage),
                           @"size":@"8"
                           };
    if ([self.messageType isEqualToString:@"order"]) {
        self.urlStr = @"messageiosApi/messageList";
    }else{
        self.urlStr = @"messageiosApi/messageSys";
    }
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:self.urlStr parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            if (self.currentPage == 1) {
                [self.cellArr removeAllObjects];
            }
            [self.cellArr addObjectsFromArray:responseObject[@"list"]];
            [self.tableView reloadData];
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
//删除消息，1为系统消息，2为订单消息
- (void)deleteMessage{
    NSDictionary * dic = @{
                           @"phone":self.phoneString,
                           @"token":self.tokenString,
                           @"msgid":self.deleteMsgID,
                           @"msgtype":self.messageType
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"messageiosApi/listdel" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self.cellArr removeObjectAtIndex:self.deleteRow];
            [self.tableView reloadData];
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"消息";
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    self.currentPage = 1;
    [self getMessageData];
}
#pragma mark - init
- (NSMutableArray *)cellArr{
    if (!_cellArr) {
        _cellArr = @[].mutableCopy;
    }return _cellArr;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - NAVI_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 100/WIDTH_6_SCALE;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerClass:[MessageTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MessageTableViewCell class])];
        _tableView.backgroundColor = getColor(mainColor);
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.currentPage = 1;
            [self getMessageData];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self.currentPage ++;
            [self getMessageData];
        }];
    }return _tableView;
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MessageTableViewCell class])];
    cell.model = self.cellArr[indexPath.row];
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellArr.count;
}

//tableView自带的左滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView setEditing:NO animated:YES];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定删除该消息？" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        WS(ws)
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            //删除事件
            ws.deleteMsgID = [NSString stringWithFormat:@"%@", [ws.cellArr[indexPath.row] objectForKey:@"id"]];
            if ([ws.messageType isEqualToString:@"order"]) {
                ws.messageType = @"2";
            }else{
                ws.messageType = @"1";
            }
            ws.deleteRow = (int)indexPath.row;
            [ws deleteMessage];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
#pragma mark - action
- (void)ifLogin{
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        [self.tabBarController setSelectedIndex:0];
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
    [self presentViewController:navi animated:YES completion:nil];
}
@end
